// src/store/index.js
import { defineStore } from "pinia";

/**
 * 用户信息和权限管理 Store
 * 存储用户信息、角色、权限等数据
 */
export const useUserStore = defineStore("user", {
  state: () => ({
    user: null, // 用户信息 { uid, username, role, ... }
    token: null, // 认证令牌
    role: null, // 用户角色: "1" 超级管理 | "2" 商品管理 | "3" 数据分析
  }),

  getters: {
    /**
     * 获取用户是否已登录
     */
    isLoggedIn: (state) => !!state.token && !!state.user,

    /**
     * 判断是否为超级管理员
     */
    isSuperAdmin: (state) => state.role === "1",

    /**
     * 判断是否为商品管理员
     */
    isGoodsAdmin: (state) => state.role === "2",

    /**
     * 判断是否为数据分析员
     */
    isDataAnalyst: (state) => state.role === "3",

    /**
     * 获取用户可见的菜单列表
     * 返回格式: { dashboard, goods, order, permission }
     */
    getVisibleMenus: (state) => {
      const role = state.role;

      const menuConfig = {
        // 超级管理员：可见所有菜单
        "1": {
          dashboard: {
            visible: true,
            readonly: false,
          },
          goods: {
            visible: true,
            readonly: false,
            children: {
              "goods-list": { visible: true, readonly: false },
              "goods-category": { visible: true, readonly: false },
              "product-spec": { visible: true, readonly: false },
              "brand-management": { visible: true, readonly: false },
            },
          },
          order: {
            visible: true,
            readonly: false,
            children: {
              "order-list": { visible: true, readonly: false },
              "refund-handle": { visible: true, readonly: false },
              "refund-reason-setting": { visible: true, readonly: false },
            },
          },
          permission: {
            visible: true,
            readonly: false,
            children: {
              "admin-list": { visible: true, readonly: false },
              "user-list": { visible: true, readonly: false },
            },
          },
        },

        // 商品管理员：可见仪表盘和商品栏（仅查看仪表盘，可编辑商品）
        "2": {
          dashboard: {
            visible: true,
            readonly: true, // 仅查看
          },
          goods: {
            visible: true,
            readonly: false,
            children: {
              "goods-list": { visible: true, readonly: false },
              "goods-category": { visible: true, readonly: false },
              "product-spec": { visible: true, readonly: false },
              "brand-management": { visible: true, readonly: false },
            },
          },
          order: {
            visible: false,
            readonly: true,
          },
          permission: {
            visible: false,
            readonly: true,
          },
        },

        // 数据分析员：可见仪表盘和订单栏（均只读）
        "3": {
          dashboard: {
            visible: true,
            readonly: true, // 仅查看
          },
          goods: {
            visible: false,
            readonly: true,
          },
          order: {
            visible: true,
            readonly: true, // 仅查看
            children: {
              "order-list": { visible: true, readonly: true },
              "refund-handle": { visible: false, readonly: true },
              "refund-reason-setting": { visible: false, readonly: true },
            },
          },
          permission: {
            visible: false,
            readonly: true,
          },
        },
      };

      return menuConfig[role] || menuConfig["3"]; // 默认返回数据分析员权限
    },
  },

  actions: {
    /**
     * 设置用户信息（登录时调用）
     * @param {Object} loginResponse - 后端返回的登录响应
     */
    setUserInfo(loginResponse) {
      const { user, token } = loginResponse.data;
      this.user = user;
      this.token = token;
      this.role = user.role;

      // 保存到 localStorage（可选，用于页面刷新时恢复）
      localStorage.setItem("userInfo", JSON.stringify(user));
      localStorage.setItem("token", token);
      localStorage.setItem("userRole", user.role);
    },

    /**
     * 从 localStorage 恢复用户信息（带验证）
     * @returns {boolean} 恢复是否成功
     */
    restoreUserInfo() {
      const userInfo = localStorage.getItem("userInfo");
      const token = localStorage.getItem("token");
      const role = localStorage.getItem("userRole");

      // 1. 检查数据完整性
      if (!userInfo || !token || !role) {
        return false;
      }

      try {
        const parsedUser = JSON.parse(userInfo);

        // 2. 验证角色值的有效性（防止篡改）
        if (!['1', '2', '3'].includes(role)) {
          console.warn('Invalid role detected:', role);
          this.clearUserInfo();
          return false;
        }

        // 3. 验证用户对象的 role 字段与保存的 role 匹配
        if (parsedUser.role !== role) {
          console.warn('Role mismatch detected');
          this.clearUserInfo();
          return false;
        }

        // 4. 验证 token 格式（简单的 JWT 格式检查）
        if (!token.includes('.') || token.split('.').length !== 3) {
          console.warn('Invalid token format detected');
          this.clearUserInfo();
          return false;
        }

        // 5. 所有验证通过，恢复数据
        this.user = parsedUser;
        this.token = token;
        this.role = role;
        return true;

      } catch (error) {
        console.error('Failed to restore user info:', error);
        this.clearUserInfo();
        return false;
      }
    },

    /**
     * 清除用户信息（退出登录时调用）
     */
    clearUserInfo() {
      this.user = null;
      this.token = null;
      this.role = null;

      localStorage.removeItem("userInfo");
      localStorage.removeItem("token");
      localStorage.removeItem("userRole");
    },
  },
});